package com.xawl.controller;

import com.github.pagehelper.PageHelper;
import com.xawl.dao.CourseMapper;
import com.xawl.pojo.CourseLearning;
import com.xawl.service.CourseService;
import com.xawl.service.UserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/course")
@CrossOrigin
public class CourseController {

    @Autowired
    @Qualifier("courseServiceImpl")
    CourseService courseService;

    @Autowired
    @Qualifier("userServiceImpl")
    UserService userService;
    
    @Autowired
    @Lazy
    CourseMapper courseMapper;

    /* 获取数据列表 */
    @ResponseBody
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    public JSONObject getList(int page, int limit) {
        PageHelper.startPage(page, limit);
        List<CourseLearning> list = courseService.queryAll();
        Integer total = courseService.getTotal();
        JSONObject json = new JSONObject();
        json.put("code", 0);
        json.put("msg", 1);
        json.put("count", total);
        json.put("data", list);
        return json;
    }

    /* 增加 */
    @RequestMapping("/add")
    public String add() {
        return "red-course-learning/red-course-learning-edit";
    }

    @RequestMapping("/addData")
    @ResponseBody
    public String addCourse(@RequestBody CourseLearning courseLearning) {
        int i = courseService.addCourse(courseLearning);
        return i != 0 ? "ok" : "error";
    }

    @RequestMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") int id) {
        model.addAttribute("clId", id);
        return "red-course-learning/red-course-learning-edit";
    }

    /* 删除 */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestBody int id) {
        courseService.deleteCourse(id);
        return "ok";
    }

    /* 删除多条记录 */
    @RequestMapping("/deletes")
    @ResponseBody
    public String deletes(@RequestBody Long[] ids) {
        int i = courseService.deleteCourses(ids);
        return i != 0 ? "ok" : "error";
    }

    /* 更新 */
    @RequestMapping("/update")
    @ResponseBody
    public String update(@RequestBody CourseLearning cl) {
        int i = courseService.updateCourse(cl);
        return i != 0 ? "ok" : "error";
    }

    /* 查看 */
    @RequestMapping("/view/{id}")
    public String view(Model model, @PathVariable("id") int id) {
        model.addAttribute("clId", id);
        return "red-course-learning/red-course-learning-view";
    }

    /* 数据回显 */
    @RequestMapping("/viewData")
    @ResponseBody
    public CourseLearning viewData(@RequestBody int id) {
        return courseService.findCourseById(id);
    }

}
